package com.lehecai.core.lottery.fetcher.lotterydraw.impl.worker;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;

import com.lehecai.core.lottery.LotteryType;
import com.lehecai.core.lottery.fetcher.lotterydraw.LotteryDraw;
import com.lehecai.core.util.CoreFetcherUtils;

/**
 * 奇虎360 重庆时时彩 开奖结果抓取
 * @author chirowong
 *
 */
public class LotteryDrawFetch200WorkerQihoo extends FrequentLotteryDrawFetchWorkerQihoo {

	public LotteryDrawFetch200WorkerQihoo(LotteryType lotteryType) {
		super(lotteryType);
	}
	
	@Override
	public LotteryDraw fetchResultDetail(String phase) {
		if (StringUtils.isEmpty(phase)) {
			logger.error("==必须指定期数==");
			return null;
		}
		String qihooPhase = phase;
		//修正彩期
		//乐和彩彩期格式 yyyyMMddxxx
		//360彩期格式 yyMMddxxx
		qihooPhase = StringUtils.substring(phase, 2, phase.length());
		LotteryType lotteryType = this.getLotteryType();
		String url = this.getResultDetailUrl(qihooPhase);
		if (url == null || url.isEmpty()) {
			logger.error("==详细页面==抓取==" + lotteryType.getName() + "==期号：" + phase
					+ "==详细地址不存在，返回null");
			return null;
		}
		String pageInfo = "详细页面" + url;
		String encoding = "GBK";
		String logHeader = "==" + pageInfo + "==抓取==" + getLotteryType().getName() + "==";

		logger.info(logHeader + "开始==");
		String data = null;

		data = CoreFetcherUtils.URLGet(url, null, encoding);
		if (data == null || data.indexOf("404 Not Found") > 0) {
			logger.error(logHeader + "data is null or 404 Not Found");
			return null;
		}
		
		LotteryDraw lotteryDraw = new LotteryDraw();
		lotteryDraw.setLotteryType(getLotteryType());
		lotteryDraw.setPhase(phase);
		return parseFrequentLotteryDraw(data, lotteryDraw, null, phase);
	}

	protected LotteryDraw parseFrequentLotteryDraw(String jsonData, LotteryDraw lotteryDraw, String encoding, String phase){
		if (jsonData == null || jsonData.isEmpty()) {
			return null;
		}
		try {
			String result = null;
			String fetchPhase = null;
			//如果是以数组形式返回
			JSONArray array = JSONArray.fromObject(jsonData);
			JSONObject object = array.getJSONObject(0);
			result = object.getString("code");
			fetchPhase = object.getString("issue");
			
			if (result == null || result.equals("")) {
				logger.error("未能从抓取数据中获取到{}期开奖结果", phase);
				return null;
			}
			
			if (fetchPhase == null || fetchPhase.equals("")) {
				logger.error("未能从抓取数据中获取到{}期彩期", phase);
				return null;
			}
			String resultStr = result;
			lotteryDraw.setResult(resultStr);
		} catch (Exception e) {
			logger.error("从360彩票解析高频彩开奖json数据发生错误,"+e.getMessage(),e);
			return null;
		}
		return lotteryDraw;
	}
}
